import _ from 'lodash';
import { getCssVariableValue } from '@/utils/utils';

// 大表头
export const getColumns = (_data) => {
  // 计算合并行
  const spanMap = {
    dataTypeName: {},
    transactionAttributesOneName: {},
    transactionAttributesTwoName: {},
    transactionAttributesThreeName: {},
  };
  for (const key in spanMap) {
    const list = _data.map((x) => x[key]);
    for (let i = 0; i < list.length; i++) {
      const val = list[i];
      let count = 1;
      while (list[i + count] === val) {
        count++;
      }
      if (count > 1) {
        spanMap[key][i] = count;
      }
      i += count - 1;
    }
  }
  const renderNum = (v) => (typeof v === 'number' ? v : '-');
  return [
    {
      name: '统计指标',
      children: [
        {
          code: 'dataTypeName',
          name: '统计指标',
          width: 100,
          align: 'center',
          lock: true,
          getCellProps: (v, r, i) => ({
            colSpan: v === '扣费收入合计' ? 4 : 1,
            rowSpan: spanMap['dataTypeName'][i],
          }),
          headerCellProps: {
            colSpan: 3,
            align: 'center',
          },
          render: (value) => {
            let node = value;
            if (node.indexOf('-') > -1) {
              node = node.split('-').map((v) => {
                return <div key={v}>{v}</div>;
              });
            }
            return node;
          },
        },
        {
          name: '统计指标',
          code: 'transactionAttributesOneName',
          width: 100,
          align: 'center',
          lock: true,
          getCellProps: (v, r, i) => ({
            colSpan: v === '电量合计' || v === '费用合计' ? 3 : 1,
            rowSpan: spanMap['transactionAttributesOneName'][i],
          }),
        },
        {
          name: '统计指标',
          code: 'transactionAttributesTwoName',
          width: 100,
          align: 'center',
          lock: true,
          getCellProps: (v, r, i) => ({
            rowSpan: spanMap['transactionAttributesTwoName'][i],
          }),
        },
        {
          name: '统计指标',
          code: 'transactionAttributesThreeName',
          width: 100,
          align: 'center',
          lock: true,
          getCellProps: (v, r, i) => ({
            rowSpan: spanMap['transactionAttributesThreeName'][i],
          }),
        },
      ],
    },
    {
      name: '当前结算电量(万kWh)',
      code: 'statementQuantity',
      width: 120,
      align: 'center',
      // render: renderNum,
      render: (value) => (_.isNull(value) ? '-' : value),
    },
    {
      name: '当前不含补贴结算平均电价(元/kWh)',
      code: 'statementEnergyPrice',
      width: 120,
      align: 'center',
      // render: renderNum,
    },
    {
      name: '当前含补贴结算平均电价(元/kWh)',
      code: 'statementSubsidyPrice',
      width: 120,
      align: 'center',
      // render: renderNum,
    },
    {
      name: '当前不含补贴结算电费收入(万元)',
      align: 'center',
      code: 'statementEnergyIncome',
      width: 120,
      render: renderNum,
    },
    {
      name: '当前含补贴结算电费收入(万元)',
      code: 'statementEnergyAndSubsidyIncome',
      align: 'center',
      width: 120,
      render: renderNum,
    },
  ];
};

// 默认
const SERIES_MAP = {
  baseElectricity: {
    name: '基数电量',
    type: 'bar',
    color: '#5E92F6',
    props: { stack: 'Electricity' },
  },
  longTermElectricity: {
    name: '中长期电量',
    type: 'bar',
    color: '#4C72B9',
    props: { stack: 'Electricity' },
  },
  spotElectricity: {
    name: '现货电量',
    type: 'bar',
    color: '#39507C',
    props: { stack: 'Electricity' },
  },
  noSubsidyNoChargeElectricity: {
    name: '不含补贴不扣费电价',
    type: 'line',
    color: '#F5BE15',
    props: { yAxisIndex: 1 },
  },
  noSubsidyAverageElectricity: {
    name: '不含补贴结算平均电价',
    type: 'line',
    color: '#F4903D',
    props: { yAxisIndex: 1 },
  },
  longTermPrice: {
    name: '中长期',
    type: 'bar',
    color: '#588AEF',
    props: { xAxisIndex: 1, yAxisIndex: 2, stack: 'another' },
  },
  spotPrice: {
    name: '现货',
    type: 'bar',
    color: '#837ADC',
    props: { xAxisIndex: 1, yAxisIndex: 2, stack: 'another' },
  },
  otherPrice: {
    name: '其他',
    type: 'bar',
    color: '#56CCF2',
    props: { xAxisIndex: 1, yAxisIndex: 2, stack: 'another' },
  },
  twoRulesPrice: {
    name: '两个细则',
    type: 'bar',
    color: '#BFEBA2',
    props: { xAxisIndex: 1, yAxisIndex: 2, stack: 'another' },
  },
  assistedServicePrice: {
    name: '辅助服务',
    type: 'bar',
    color: '#5AD8A6',
    props: { xAxisIndex: 1, yAxisIndex: 2, stack: 'another' },
  },
};

// 辽宁
const NL_SERIES_MAP = {
  longTermElectricity: SERIES_MAP.longTermElectricity,
  spotElectricity: SERIES_MAP.spotElectricity,
  noSubsidyNoChargeElectricity: SERIES_MAP.noSubsidyNoChargeElectricity,
  noSubsidyAverageElectricity: SERIES_MAP.noSubsidyAverageElectricity,
  longTermPrice: SERIES_MAP.longTermPrice,
  spotPrice: SERIES_MAP.spotPrice,
  otherPrice: SERIES_MAP.otherPrice,
  assistedServicePrice: SERIES_MAP.assistedServicePrice,
};

// 黑龙江
const HLJ_SERIES_MAP = {
  longTermElectricity: SERIES_MAP.longTermElectricity,
  spotElectricity: SERIES_MAP.spotElectricity,
  noSubsidyNoChargeElectricity: SERIES_MAP.noSubsidyNoChargeElectricity,
  noSubsidyAverageElectricity: SERIES_MAP.noSubsidyAverageElectricity,
  longTermPrice: SERIES_MAP.longTermPrice,
  spotPrice: SERIES_MAP.spotPrice,
  otherPrice: SERIES_MAP.otherPrice,
  assistedServicePrice: SERIES_MAP.assistedServicePrice,
};

//陕西
const SAX_SERIES_MAP = {
  assistedServicePrice: SERIES_MAP.assistedServicePrice,
  longTermElectricity: SERIES_MAP.longTermElectricity,
  longTermPrice: SERIES_MAP.longTermPrice,
  noSubsidyAverageElectricity: SERIES_MAP.noSubsidyAverageElectricity,
  noSubsidyNoChargeElectricity: SERIES_MAP.noSubsidyNoChargeElectricity,
  otherPrice: SERIES_MAP.otherPrice,
  spotElectricity: SERIES_MAP.spotElectricity,
  spotPrice: SERIES_MAP.spotPrice,
  twoRulesPrice: SERIES_MAP.twoRulesPrice,
};

const chartBaseOption = () => {
  const isSmallScreen = window.innerHeight < 800; // 你可以根据实际需求调整阈值
  const gridHeight = isSmallScreen ? '30%' : '40%';
  return {
    grid: [
      { left: 60, right: 60, top: 24, height: isSmallScreen ? '28%' : '38%' },
      { left: 60, right: 60, bottom: 24, height: gridHeight },
    ],
    axisPointer: {},
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
      pageIconColor: getCssVariableValue('--bd-primary'),
      pageTextStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    tooltip: {
      textStyle: { lineHeight: 24 },
    },
    xAxis: [
      {
        type: 'category',
        gridIndex: 0,
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          alignWithLabel: true,
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
      {
        type: 'category',
        gridIndex: 1,
        axisLabel: {
          show: false,
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: { show: false },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '电量(万kWh)',
        gridIndex: 0,
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--font-a10'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
      {
        type: 'value',
        name: '电价(元/kWh)',
        gridIndex: 0,
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
      {
        type: 'value',
        name: '收入(万元)',
        gridIndex: 1,
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
    ],
    series: [],
  };
};

export const fmtMonthData = (_data, _type = 'PHBSX') => {
  let monthChart = null;
  let monthTable = [];
  let monthColumns = [];
  if (!_data) {
    return {
      monthChart,
      monthTable,
      monthColumns,
    };
  }
  const months = _data?.yearMonth || [];
  monthChart = _.cloneDeep(chartBaseOption());
  monthColumns = [
    {
      code: 'type',
      name: '类型',
      align: 'center',
      width: 170,
      lock: true,
    },
    ...months.map((mm) => ({
      code: mm,
      name: mm,
      align: 'center',
      width: 120,
    })),
  ];
  // 处理不需要展示的字段
  const NOT_ENUM = {
    PDBLJ: ['baseElectricity'],
    PXBSX: ['baseElectricity'],
  };
  const SERIES_MAP_EMNU = {
    PDBLN: NL_SERIES_MAP,
    PDBLJ: HLJ_SERIES_MAP,
    PXBSX: SAX_SERIES_MAP,
  };
  let SERIES = SERIES_MAP_EMNU[_type] || SERIES_MAP;

  if (NOT_ENUM[_type]) {
    NOT_ENUM[_type].forEach((key) => delete SERIES[key]);
  }
  for (const code in SERIES) {
    let rowTemp = {
      type: SERIES[code]?.name || '',
    };
    months.forEach((mm, i) => {
      rowTemp[mm] = _data?.[code]?.[i] ?? '';
    });
    monthTable.push(rowTemp);

    const seriesData = Array.isArray(_data?.[code]) ? _data[code] : months.map(() => '');
    monthChart.series.push({
      ...SERIES[code],
      data: seriesData,
    });
  }
  monthChart.xAxis[0].data = months;
  monthChart.xAxis[1].data = months;

  return {
    monthChart,
    monthTable,
    monthColumns,
  };
};
